# -*- coding:utf-8 -*-
import os
import cgi
import ast
import time
from flask import jsonify
from flask import current_app
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask import flash
from flask_login import login_required
from flask_login import current_user
from flask_uploads import UploadSet, IMAGES
from sqlalchemy import desc, asc
from qiniu import Auth
from qiniu import put_data
from pypinyin import lazy_pinyin

from app import db
from app.models.site_setting import LinkSite, Navigation, Carousel, Carousel_APP, HotCity
from app.models.site_setting import AttrBrand, AttrCarModel, Third_Party_Code
from app.models.site_setting import BusinessScope as BS
from app.models.business import Car
from app.views.siteSetting import siteSetting
from app.tools.permission import permission
from app.tools.log import log
from app.tools.redis_op import Operator

op = Operator()

set_carousel = UploadSet('carousel', IMAGES)

range_field = ('price', 'car_age', 'mileage', 'exhaust')


def signin_required():
    if not current_user.is_authenticated:
        return redirect(url_for('auth.login'))


siteSetting.before_request(signin_required)


@siteSetting.before_request
@login_required
@permission(['setup', 'manage', 'admin', 'super'])
def check_permission():
    return


def add_carousel(img):  # 保存图片
    q = Auth(current_app.config['QINIU_ACCESS_KEY'], current_app.config['QINIU_SECRET_KEY'])
    bucket_name = current_app.config['QINIU_BUCKET_NAME']
    if '.' in img.filename:
        ext = os.path.splitext(img.filename)[-1]
        fname = str(int(time.time())) + ext
    else:
        fname = str(int(time.time()))


    token = q.upload_token(bucket_name, expires=3600)
    ret, info = put_data(token, key=fname, data=img.stream)

    key = ret['key']
    domain = 'http://omdcfjxex.bkt.clouddn.com/'
    file_url = domain + key
    if info.status_code == 200:
        return file_url, True
    else:
        return None, False


def brand_and_car_model(key, ms):  # 按照格式 返回 品牌和车型
    """
    key: brand or car_model
    ms: [instance]
    return: {'brand': [instance.name]}
    [{"sort":1, 'id':'xx', 'value':xx}] 按sort排序的列表  或 []
    """
    d = {}
    l = []
    for m in ms:
        d1 = {}
        d1['sort'] = m.sort
        d1['id'] = m.id
        d1['value'] = m.name
        l.append(d1)
    d[key] = l
    return d


def is_digit_or_float(s):  # 判断范围是否合法
    if s == '':
        return True
    try:
        num = eval(s)
    except (SyntaxError, NameError):
        return False
    return True


name_dict = dict(
    brand=u'品牌',
    price=u'价格范围',
    car_model=u'车型',
    car_age=u'车龄',
    mileage=u'里程',
    gearbox=u'变速箱类型',
    exhaust=u'排量范围',
    seat=u'座位数',
    standard=u'排放标准',
    color=u'颜色',
)


##############################################
################### 友情链接 ###################
@siteSetting.route('/links')
def link_index():
    links = LinkSite.query.all()
    return render_template('siteSetting/link.html',
                           links=links)


@siteSetting.route('/links/delete/<int:link_id>', methods=['GET'])
def delete_one(link_id):
    if not link_id:
        return render_template('404.html'), 404
    link = LinkSite.query.filter_by(id=link_id).first()
    if not link:
        message = u'已经删除过了'
        flash(message)
        return redirect(url_for('.link_index'))
    LinkSite.delete(link_id)
    log(u'删除友情链接 {}'.format(link.name))

    return redirect(url_for('.link_index'))


@siteSetting.route('/links/delete', methods=['POST'])
def delete_many():
    form = request.get_json()
    print 'log delete form', form
    not_found = []
    for link_id in form:
        link = LinkSite.query.filter_by(id=link_id).first()
        if not link:
            not_found.append(str(link_id))
            continue
        LinkSite.delete(link_id)
        log(cgi.escape(u'删除友情链接 {}'.format(link.name)))

    return jsonify(dict(
        message=u'删除成功',
        success=True
    ))
    # return render_template('siteSetting/link.html')


@siteSetting.route('/links/new', methods=['GET', 'POST'])
def new_link():
    if request.method == 'POST':
        if count_link():
            flash(u'友情链接超过12个')
            return redirect(url_for('.link_index'))
        form = request.form
        name = form.get('name')
        if len(name) > 20:
            flash(u'站点名称太长')
            return redirect(url_for('.link_index'))
        link = LinkSite.new(form)
        log(cgi.escape(u'添加友情链接 {}'.format(link.name)))
        flash(u'添加成功！')
        return redirect(url_for('.link_index'))
    return render_template('siteSetting/new_link.html')


@siteSetting.route('/links/show/<int:link_id>', methods=['GET'])
def show_link(link_id):
    if not link_id:
        return render_template('404.html'), 404
    link = LinkSite.query.filter_by(id=link_id).first_or_404()
    link.state = True
    link.save()
    return redirect(url_for('.link_index'))


@siteSetting.route('/links/hide/<int:link_id>', methods=['GET'])
def hide_link(link_id):
    if not link_id:
        return render_template('404.html'), 404
    link = LinkSite.query.filter_by(id=link_id).first_or_404()
    link.state = False
    link.save()
    return redirect(url_for('.link_index'))


@siteSetting.route('/links/update/<int:link_id>', methods=['GET', 'POST'])
def update_link(link_id):
    if request.method == 'POST':
        form = request.form
        link = LinkSite.query.filter_by(id=link_id).first_or_404()
        link.update(link_id, form)

        link.save()
        log(cgi.escape(u'更新友情链接 {}'.format(form.get('name'))))
        flash(u'更新成功！')
        return redirect(url_for('.link_index'))
    link = LinkSite.query.filter_by(id=link_id).first_or_404()

    return render_template('siteSetting/edit_link.html',
                           link_id=link_id,
                           link=link)


@siteSetting.route('/links/sort', methods=['POST'])
def sort_link():
    l = request.get_json()
    LinkSite.__sort(l)
    return jsonify({
        'success': True
    })


@siteSetting.route('/links/count', methods=['GET', 'POST'])
def count_link():
    l = LinkSite.query.all()
    return len(l) > 12


##############################################
################### 热门城市 和 业务城市 #########
@siteSetting.route('/hot', methods=['GET'])
def city_index():
    citys = HotCity.query.all()
    b_citys = BS.query.all()
    return render_template('siteSetting/hot_city.html',
                           citys=citys,
                           b_citys=b_citys
                           )


@siteSetting.route('/hot/save_city', methods=['POST'])
def save_city():
    city = request.values.get('city').split('/')[1]
    citys = HotCity.query.all()
    if len(citys) > 9:
        return jsonify({"msg": u"热门城市超过10个！"})
    elif len(BS.query.filter_by(city=city).all()) == 0:
        return jsonify({"msg": u"该热门城市不存在于业务范围内！"})
    elif len(HotCity.query.filter_by(city=city).all()) > 0:
        return jsonify({"msg": u"不能重复添加！"})
    elif city and city != '-1':
        f = dict(city=city)
        HotCity.new(f)
        log(cgi.escape(u'添加热门城市 {}'.format(city)))
        ename = ''.join(lazy_pinyin(city))
        op.hset('hot_city', ename, city)
    else:
        return jsonify({"msg": u"请选择城市！"})
    return jsonify({"msg": u"添加成功！"})


@siteSetting.route('/hot/delete', methods=['POST'])
def delete_city():
    form = request.form
    citys = form.keys()
    if not citys:
        flash(u'还没有选择城市！', category='error')
        return redirect(url_for('.city_index'))
    for city_id in citys:
        city = HotCity.query.get(city_id).city
        HotCity.delete(city_id)
        log(cgi.escape(u'删除热门城市 {}'.format(city)))
        ename = ''.join(lazy_pinyin(city))
        op.r.hdel('hot_city', ename)
    flash(u'删除成功！')
    return redirect(url_for('.city_index'))


# 业务范围城市
@siteSetting.route('/business/save_city', methods=['POST'])
def business():
    city = request.values.get('city').split('/')[1]
    if BS.query.filter_by(city=city).count() > 0:
        return jsonify({"msg": u"不能重复添加！"})
    elif city != '-1':
        db.session.add(BS(city=city))
        db.session.commit()
        ename = ''.join(lazy_pinyin(city))
        first = ename[0]
        city_list = op.hgetall('city_list')
        if not first in city_list.keys():
            op.hset('city_list', first, {ename: city})
        else:
            city_list = op.hgetall('city_list')
            dist = ast.literal_eval(city_list.get(first))
            dist[ename] = city
            op.hset('city_list', first, dist)
        log(cgi.escape(u'添加业务范围城市 {}'.format(city)))
    else:
        return jsonify({"msg": u"请选择城市！"})
    return jsonify({"msg": u"添加成功！"})


@siteSetting.route('/business/delete', methods=['POST'])
def business_delete():
    form = request.form
    citys = form.keys()

    if not citys:
        flash(u'还没有选择城市！', category='error')
        return redirect(url_for('.city_index'))
    for city_id in citys:
        city = BS.query.get(city_id).city
        BS.delete(city_id)
        ename = ''.join(lazy_pinyin(city))
        first = ename[0]
        city_list = op.hgetall('city_list')
        dist = ast.literal_eval(city_list.get(first))
        dist.pop(ename)
        if len(dist) == 0:
            op.r.hdel('city_list', first)
        else:
            op.hset('city_list', first, dist)
        log(cgi.escape(u'删除业务范围城市 {}'.format(city)))
    flash(u'删除成功！')
    return redirect(url_for('.city_index'))


##############################################
################### 车辆属性 ###################
@siteSetting.route('/carAttribute', methods=['GET'])
def attr_index():
    brands = AttrBrand.query.order_by(AttrBrand.sort).all()
    brand = brand_and_car_model('brand', brands)
    car_models = AttrCarModel.query.order_by(AttrCarModel.sort).all()
    car_model = brand_and_car_model('car_model', car_models)
    price = op.flat_all('price')  # [{"sort":1, 'id':'xx', 'value':xx}] 按sort排序的列表  或 []
    car_age = op.flat_all('car_age')
    mileage = op.flat_all('mileage')
    gearbox = op.flat_all('gearbox')
    exhaust = op.flat_all('exhaust')
    seat = op.flat_all('seat')
    standard = op.flat_all('standard')
    color = op.flat_all('color')

    price = {'price': price}
    car_age = {'car_age': car_age}
    mileage = {'mileage': mileage}
    gearbox = {'gearbox': gearbox}
    exhaust = {'exhaust': exhaust}
    seat = {'seat': seat}
    standard = {'standard': standard}
    color = {'color': color}
    res = render_template('siteSetting/car_attr.html',
                          brand=brand,
                          price=price,
                          car_model=car_model,
                          car_age=car_age,
                          mileage=mileage,
                          gearbox=gearbox,
                          exhaust=exhaust,
                          seat=seat,
                          standard=standard,
                          color=color,
                          name_dict=name_dict,
                          len=len,
                          range=range,
                          )
    return res


# 车辆的具体一个属性页面
@siteSetting.route('/carAttribute/edit/<field>', methods=['GET'])
def car_attr_edit(field):
    context = dict(
        name_dict=name_dict,
    )
    if field == 'brand':  # 品牌和车型单独处理
        brands = AttrBrand.query.order_by(AttrBrand.sort).all()
        r = {}
        l = []
        for m in brands:
            a = {}
            a['id'] = m.id
            a['value'] = m.name
            a['sort'] = m.sort
            l.append(a)
        r[field] = l
        return render_template('siteSetting/car_attr_edit.html',
                               d=r,
                               name_dict=name_dict,
                               len=len,
                               range=range
                               )

    elif field == 'car_model':  # 品牌和车型单独处理
        car_models = AttrCarModel.query.order_by(AttrCarModel.sort).all()
        r = {}
        l = []
        for m in car_models:
            a = {}
            a['id'] = m.id
            a['value'] = m.name
            a['sort'] = m.sort
            l.append(a)
        r[field] = l
        return render_template('siteSetting/car_attr_edit.html',
                               d=r,
                               name_dict=name_dict,
                               len=len,
                               range=range
                               )
    else:

        r = op.flat_all(field)  # [{"sort":1, 'id':'xx', 'value':xx}]  或 []
        d = {field: r}  # {filed: [{"sort":1, 'id':'xx', 'value':xx}] } 或 {field: []}
        context = dict(
            name_dict=name_dict,
            d=d,
        )
        if field in range_field:  # 如果是带范围的字段 额外返回范围
            r = op.hgetall('range_rel')
            range_rel = {}
            for k, v in r.items():
                range_rel[k] = eval(v)
            return render_template('siteSetting/car_attr_edit.html',
                                   rel=range_rel,
                                   **context
                                   )
        elif field == 'color':  # 如果是颜色字段 额外返回颜色值
            color_values = op.hgetall('color_values')
            return render_template('siteSetting/car_attr_edit.html',
                                   color_values=color_values,
                                   len=len,
                                   range=range,
                                   **context
                                   )
        else:
            return render_template('siteSetting/car_attr_edit.html',
                                   len=len,
                                   range=range,
                                   **context
                                   )


@siteSetting.route('/carAttribute/new_item/<key>', methods=['POST'])
def car_attr_new_item(key):
    form = request.form
    item = form.get(key, '')
    if not item:
        flash(u'保存失败，提交信息不全。')
        return redirect(url_for('.car_attr_edit', field=key))

    if key == 'brand':
        if AttrBrand.query.filter_by(name=item).first():
            flash(u'该品牌已存在！')
            return redirect(url_for('.car_attr_edit', field=key))
        pinyin_list = lazy_pinyin(item)
        ename = ''.join(pinyin_list)
        first_ename = ''.join(i[0] for i in pinyin_list)
        data = dict(
            name=item,
            ename=ename,
            first_ename=first_ename,
        )
        b = AttrBrand(**data)
        b.save()
        b.sort = b.id
        b.save()
        op.hset('brand', b.id, (item, b.sort))  # {'1': ('大众', '1')}
        print u'添加品牌：', item
        log(cgi.escape(u'在车辆属性添加品牌：{}'.format(item)))

    elif key == 'car_model':
        data = dict(
            name=item,
        )
        b = AttrCarModel(**data)
        b.save()
        b.sort = b.id
        b.save()
        log(cgi.escape(u'在车辆属性添加车型：{}'.format(item)))
        op.hset('car_type', b.id, (item, b.sort))
    elif key == 'color':
        color_value = form.get("color_value")
        count = op.r.hlen('color')
        id = str(max([int(i) for i in op.r.hkeys(key)]) + 1)  # 找出id最大的项，新增项id以此往上增
        op.hset('color', id, (item, id))
        print 'color new', color_value, count
        op.hset('color_values', id, color_value)
        flash(u'添加成功！')
        return redirect(url_for('.car_attr_edit', field=key))
    else:
        id = str(max([int(i) for i in op.r.hkeys(key)]) + 1)
        op.hset(key, id, (item, id))

        # 带范围的字段 把范围存到 range_rel 中
        if key in range_field:
            range = form.getlist('range')
            for r in range:
                if not is_digit_or_float(r):
                    flash(u'不是数字，请重新输入')
                    return redirect(url_for('.car_attr_edit', field=key))
            try:
                range = [float(i) for i in range]
                range.sort()
                range = [str(i) for i in range]
            except ValueError:  # except ['5.4', '']
                pass
            op.hset('range_rel', key + id, range)
    flash(u'添加成功！')
    return redirect(url_for('.car_attr_edit', field=key))


@siteSetting.route('/carAttribute/update/<field>', methods=['POST'])
def car_attr_update(field):
    form = request.form
    field_list = form.getlist(field)
    if field == 'brand':  # 品牌
        ids = form.getlist('id')

        brand = {}
        for id in ids:
            b = AttrBrand.query.get(id)
            sort = ids.index(id)
            b.name = field_list[sort]
            b.sort = str(sort + 1)
            b.save()
            brand[b.id] = (b.name, b.sort)
            op.hsetall('brand', brand)
        flash(u'更新成功！')
        return redirect(url_for('.attr_index'))
    elif field == 'car_model':  # 车型
        ids = form.getlist('id')
        car_type = {}
        for id in ids:
            b = AttrCarModel.query.get(id)
            sort = ids.index(id)
            b.name = field_list[sort]
            b.sort = str(sort + 1)
            b.save()
            car_type[b.id] = (b.name, b.sort)
            op.hsetall('car_type', car_type)
        flash(u'更新成功！')
        return redirect(url_for('.attr_index'))
    elif field == 'color':
        color_value_list = form.getlist('color_value')
        if len(color_value_list) != len(set(color_value_list)):
            flash(u'不能填入颜色相同的值, 保存失败')
            return redirect(url_for('.car_attr_edit', field=field))
        color_list = form.getlist('color')
        ids = form.getlist('id')
        for index, id in enumerate(ids):
            color_name = color_list[index]
            color_value = color_value_list[index]
            sort = str(index + 1)
            op.hset('color', id, (color_name, sort))
            op.hset('color_values', id, color_value)
        flash(u'保存成功')
        return redirect(url_for('.car_attr_edit', field=field))
    else:
        if not len(field_list) == len(set(field_list)):
            flash(u'保存失败，填入了重复的名字')
            return redirect(url_for('.car_attr_edit', field=field))
        if field in range_field:  # 带范围的字段
            rank = form.getlist('range')
            ids = form.getlist('id')
            d = {}
            for i in rank:
                if not is_digit_or_float(i):
                    flash(u'填入了非数字，请重新填写。')
            for index, id in enumerate(ids):
                name = field_list[index]
                op.hset(field, id, (name, str(index + 1)))
                a1 = rank.pop(0)
                a2 = rank.pop(0)
                try:
                    l = [float(a1), float(a2)]
                    l.sort()
                    l = [str(o) for o in l]
                except ValueError as e:
                    l = [a1, a2]
                d[field + id] = l
                op.hsetall('range_rel', d)
        else:  # 不带范围
            ids = form.getlist('id')
            for index, id in enumerate(ids):
                name = field_list[index]
                sort = str(index + 1)
                op.hset(field, id, (name, sort))

    flash(u'更新成功！')
    return redirect(url_for('.attr_index'))


@siteSetting.route('/carAttribute/delete', methods=['POST'])
def car_attr_delete():
    form = request.get_json()
    key = form.keys()[0]
    print key, 'form:', form
    rtn = jsonify(dict(
        message=u'删除成功',
        success=True
    ))
    ids = form[key]
    # brand form: {u'brand': [u'2', u'6', u'7', u'15']}
    # car_model form: {u'car_model': [u'2', u'6', u'10']}
    # color form: {u'color': [u'1', u'2', u'6']}

    if key == 'brand':  # 品牌不删除
        for id in ids:
            if Car.query.filter_by(brand=id).first():
                return jsonify(dict(
                    message=u'该品牌尚有车辆存在！',
                    success=True
                ))
    elif key == 'car_model':  # 车型不删除
        for id in ids:
            if Car.query.filter_by(car_type=id).first():
                return jsonify(dict(
                    message=u'该车型尚有车辆存在！',
                    success=True
                ))
    elif key == 'color':
        for id in ids:
            if Car.query.filter_by(color=id).first():
                return jsonify(dict(
                    message=u'该颜色尚有车辆存在！',
                    success=True
                ))
    elif key == 'gearbox':
        for id in ids:
            if Car.query.filter_by(type_of_gearbox=id).first():
                return jsonify(dict(
                    message=u'该变速箱类型尚有车辆存在！',
                    success=True
                ))
    elif key == 'seat':
        for id in ids:
            if Car.query.filter_by(number_of_seats=id).first():
                return jsonify(dict(
                    message=u'该座位数量尚有车辆存在！',
                    success=True
                ))
    elif key == 'standard':
        for id in ids:
            if Car.query.filter_by(emission_standard=id).first():
                return jsonify(dict(
                    message=u'该排放标准尚有车辆存在！',
                    success=True
                ))

    for id in ids:
        if key == 'color':  # 删除redis里的color_value
            op.r.hdel('color_values', id)
        elif key in range_field:  # 删除redis里的范围
            range_key = key + id
            op.r.hdel('range_rel', range_key)
        if key == 'brand':
            brand = AttrBrand.query.filter_by(id=id).first()
            db.session.delete(brand)
            db.session.commit()
        op.r.hdel(key, id)
    return rtn


##############################################
################### 导航栏 ###################
@siteSetting.route('/nav', methods=['GET'])
def nav_index():
    navs = []
    for i in range(1, 4):
        n = Navigation.query.get(i)
        navs.append(n)
    return render_template('siteSetting/nav.html', navs=navs)


@siteSetting.route('/nav/update', methods=['POST'])
def nav_update():
    forms = request.get_json()
    i = 1
    for form in forms:
        try:
            Navigation.update(i, form)
        except AttributeError:
            n = Navigation(form)
            n.save()
            log(cgi.escape(u'增加导航栏 {}'.format(form.get('name'))))
        i += 1
    return jsonify(dict(
        message=u'更新成功',
        success=True
    ))


##############################################
################### 轮播图 PC和APP端 ###################
@siteSetting.route('/')
@siteSetting.route('/carousel', methods=['GET'])
def carousel_index():
    path = url_for('static', filename='img/default.jpg')  # 如果没有数据就显示默认图片
    cs = Carousel.query.order_by(desc(Carousel.sort)).all()
    cas = Carousel_APP.query.order_by(desc(Carousel_APP.sort)).all()
    while len(cs) < 5:  # 增加一个占位
        cs.append(dict(
            path=path,
            url='',
            id=str(len(cs) + 1)
        ))
    while len(cas) < 5:  # 增加一个占位
        cas.append(dict(
            path=path,
            url='',
            id=str(len(cas) + 1)
        ))
    return render_template('siteSetting/carousel.html',
                           cs=cs,
                           cas=cas)


@siteSetting.route('/carousel/upload', methods=['POST'])
def upload_one_pic():  # 上传一张保存一张
    form = request.form
    type = request.args.get('type')
    f = request.files.get('file')
    id = form.get('input-sort-id')
    if type == 'pc':
        c = Carousel.query.get(id)
        count = Carousel.query.count()
        if not c:
            c = Carousel()
    else:
        c = Carousel_APP.query.get(id)
        count = Carousel_APP.query.count()
        if not c:
            c = Carousel_APP()

    path, status = add_carousel(f)
    if status is False:
        flash(u'保存失败，请检查文件')
        return redirect(url_for('.carousel_index'))
    c.change_path(path)
    c.sort = int(count) + 1
    c.save()
    log(u'更新轮播图图片 {}'.format(f.filename))
    flash(u'保存成功！')
    return redirect(url_for('.carousel_index'))


@siteSetting.route('/carousel/save/pc', methods=['POST'])
def save_pc():
    form = request.get_json()
    a = 1
    for i in range(len(form)):
        d = form[i]
        id = d['id']
        url = d['url']
        c = Carousel.query.get(id)
        if c:
            c.sort = a
            if c.url != url:
                c.url = url
            c.save()
            log((cgi.escape(u'更新PC端轮播图地址 {}'.format(url))))
            a += 1
    flash(u'更新成功')
    return jsonify(dict(
        message=u"更新成功",
        success=True
    ))


@siteSetting.route('/carousel/save/app', methods=['POST'])
def save_app():
    form = request.get_json()
    a = 1
    for i in range(len(form)):
        d = form[i]
        id = d['id']
        url = d['url']
        c = Carousel_APP.query.get(id)
        if c:
            c.sort = a
            c.url = url
            c.save()
            log((cgi.escape(u'更新APP端轮播图地址 {}'.format(url))))
            a += 1
    flash(u'更新成功')
    return jsonify(dict(
        message=u"更新成功",
        success=True
    ))


@siteSetting.route('/carousel/delete/pc', methods=['POST'])
def carousel_delete():
    form = request.get_json()
    print form
    for id, v in form.items():
        c = Carousel.query.get(id)
        if c and v:
            c.remove()
            log(u'删除PC端轮播图')

    return jsonify(dict(
        message=u'删除成功',
        success=True,
        next=url_for('.carousel_index')
    ))


@siteSetting.route('/carousel/delete/app', methods=['POST'])
def carousel_delete_app():
    form = request.get_json()
    for id, v in form.items():
        c = Carousel_APP.query.get(id)
        if c and v:
            c.remove()
            log(u'删除APP端轮播图')

    return jsonify(dict(
        message=u'删除成功',
        success=True,
        next=url_for('.carousel_index')
    ))


##############################################
################### 广告位 ###################

##############################################
################### 第三方代码 ###################
@siteSetting.route('/code', methods=['GET'])
def code_index():
    t = Third_Party_Code.query.get(1)

    return render_template('siteSetting/code.html', t=t)


@siteSetting.route('/code/post', methods=['POST'])
def save_code():
    form = request.form
    code = form.get('code', '')
    t = Third_Party_Code.query.get(1)
    if not t:
        t = Third_Party_Code()
    t.code = code
    t.save()
    log(u'更新第三方代码')
    flash(u'保存代码成功')
    return redirect(url_for('.code_index'))
